package com.yzd.learnjava.io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import com.yzd.learnjava.util.Print;

public class ZipCompress {
	public static void main(String[] args) throws IOException {
		FileOutputStream f = new FileOutputStream("test.zip");
		CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
		ZipOutputStream zos = new ZipOutputStream(csum);
		BufferedOutputStream out = new BufferedOutputStream(zos);
		zos.setComment("A test of Java zipping");
		for(String s : "bb dd ee rr tt y u ere rwer ewrwerre dfg fdf ds wer".split(" ")) {
			Print.print("Write file : " + s);
			BufferedReader reader = new BufferedReader(new StringReader(s));
			zos.putNextEntry(new ZipEntry(s));
			int c ;
			while((c = reader.read()) != -1) {
				out.write(c);
			}
			reader.close();
			out.flush();
		}
		out.close();
		Print.print("Checksum : " + csum.getChecksum().getValue());
		
		Print.print("Reading File");
		FileInputStream fi = new FileInputStream("test.zip");
		CheckedInputStream csumi = new CheckedInputStream(fi, new Adler32());
		ZipInputStream in2 = new ZipInputStream(csumi);
		BufferedInputStream bis = new BufferedInputStream(in2);
		ZipEntry ze ;
		while((ze = in2.getNextEntry()) != null) {
			Print.print("Reading file : " + ze);
			int x ;
			while((x = bis.read()) != -1) {
				System.out.write(x);
			}
		}
		Print.print("Checksum : " + csumi.getChecksum().getValue());
		bis.close();
		
		ZipFile zf = new ZipFile("test.zip");
		Enumeration e = zf.entries();
		while(e.hasMoreElements()) {
			ZipEntry ze2 = (ZipEntry)e.nextElement();
			Print.print("File:" + ze2);
		}
	}
}
